﻿using BootstrapBlazor.Components;
using CodeMan.Application;
using CodeMan.Application.Contracts.ClassGens;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using Volo.Abp;

namespace CodeManDesktopBlazor
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly IHost _host;
        private readonly IAbpApplicationWithExternalServiceProvider _application;
        public string Version;

        public App()
        {

            Version = Assembly.GetEntryAssembly().GetFileVersion();
            var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";
            Log.Logger = new LoggerConfiguration()
#if DEBUG
                .MinimumLevel.Debug()
#else
                .MinimumLevel.Information()
#endif
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Logger(c => c.Filter.ByIncludingOnly(Matching.WithProperty<string>("SourceContext", p => p.StartsWith("Microsoft.EntityFrameworkCore")))
                                .WriteTo.Async(c => c.File("Logs/EFLog-.txt", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 10)))
                .WriteTo.Logger(c => c.Filter.ByIncludingOnly(a => a.Level == LogEventLevel.Error)
                                .WriteTo.Async(c => c.File("Logs/Error-.txt", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 31)))
                .WriteTo.Logger(c => c.Filter.ByIncludingOnly(a => a.Level == LogEventLevel.Warning)
                                .WriteTo.Async(c => c.File("Logs/Warning-.txt", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 15)))
                .WriteTo.Async(c => c.File("Logs/logAll-.txt", outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 15))
                .CreateLogger();

            _host = CreateHostBuilder();
            _application = _host.Services.GetService<IAbpApplicationWithExternalServiceProvider>();
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            try
            {
                Log.Information("Starting WPF host.");
                await _host.StartAsync();
                Initialize(_host.Services);

                GData.currMainWindow = _host.Services.GetService<MainWindow>();
                GData.currMainWindow.Show($"CodeMan-->V{Version}");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                MessageBox.Show(ex.Message);
                Environment.Exit(0);
            }
        }
        public MainWindow GetMainWindow()
        {
            return _host.Services.GetService<MainWindow>();
        }
        protected override async void OnExit(ExitEventArgs e)
        {
            _application.Shutdown();
            await _host.StopAsync();
            _host.Dispose();
            Log.CloseAndFlush();
        }

        private void Initialize(IServiceProvider serviceProvider)
        {
            _application.Initialize(serviceProvider);
        }

        private IHost CreateHostBuilder()
        {
            return Host
                .CreateDefaultBuilder(null)
                .UseAutofac()
                .UseSerilog()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddApplication<CodeManDesktopModule>();
                    addAddBlazorWebView(services);
                }).Build();
        }
        public void addAddBlazorWebView(IServiceCollection serviceCollection)
        {
            serviceCollection.AddBlazorWebView();
            // AddBootstrapBlazor Configure
            serviceCollection.Configure<BootstrapBlazorOptions>(op =>
            {
                op.ToastDelay = 4000;
                op.SupportedCultures = new List<string> { "zh-CN", "en-US" };
            });

            serviceCollection.AddBootstrapBlazor(localizationAction: localizationAction =>
            {
                // 设置 Json 格式嵌入式资源文件
                localizationAction.AdditionalJsonAssemblies = new[] { typeof(MainWindow).Assembly };
                // 设置 Json 物理路径文件
                //options.AdditionalJsonFiles = new string[]
                //{

                //};
            });
            //code show
            //serviceCollection.
            //add db 
            serviceCollection.AddTableDemoDataCodeManService();

            //add Resources services 
            Resources.Add("services", serviceCollection.BuildServiceProvider());

            GData.SetCurrentCulture(GData.DefaultThreadCurrentCulture);

        }
    }
}
